PHP str_replace() 函數(shù)
定義和用法
str_replace() 函數(shù)使用一個(gè)字符串替換字符串中的另一些字符。
語法
str_replace(find,replace,string,count)
參數(shù) | 描述 |
---|---|
find | 必需。規(guī)定要查找的值。 |
replace | 必需。規(guī)定替換 find 中的值的值。 |
string | 必需。規(guī)定被搜索的字符串。 |
count | 可選。一個(gè)變量,對(duì)替換數(shù)進(jìn)行計(jì)數(shù)。 |
提示和注釋
注釋:該函數(shù)對(duì)大小寫敏感。請(qǐng)使用 str_ireplace() 執(zhí)行對(duì)大小寫不敏感的搜索。
注釋:該函數(shù)是二進(jìn)制安全的。
例子
例子 1
<?php
echo str_replace("world","John","Hello world!")
;
?>
輸出:
Hello John!
例子 2
在本例中,我們將演示帶有數(shù)組和 count 變量的 str_replace() 函數(shù):
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i)
);
echo "Replacements: $i";
?>
輸出:
Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1
例子 3
<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr)
);
?>
輸出:
Array ( [0] => B [1] => [2] => ! )